/**
 * 标签页面板组件
 */
import React from 'react';

import { LocaleProvider } from 'antd';

import MemoryRouter from 'react-router/MemoryRouter';

import { Route, Switch, withRouter } from 'react-router';

import zh_CN from 'antd/lib/locale-provider/zh_CN';

class TabPanelRouter extends React.PureComponent {

    goto = (path, param, cb) => {
        const { history } = this.props;
        history.push(path, param);
        if (cb) {
            setTimeout(function () { cb(); });
        }
    }

    render() {

        const { contentMap, location } = this.props;
        const pathSnippets = location ? location.pathname.split('/').filter(i => i) : [];

        if (contentMap && contentMap['/'] && pathSnippets.length === 0) {
            pathSnippets.push('');
        }

        return (
            <React.Fragment >
                {this.props.children}
            </React.Fragment>
        );
    }
}

const TabPanelWithRouter = withRouter(TabPanelRouter);

export default class UITabPanel extends React.PureComponent {
    
    goto = (path, param, cb) => {
        this.panelRouter.goto(path, param, cb);
    }

    render() {
        const { contentMap, pageInstance } = this.props;

        const routeList = [];

        if (contentMap) {
            for (const key of Object.keys(contentMap)) {
                const routeItem = contentMap[key];
                const { getComponent } = routeItem;
                routeList.push(
                    <Route key={key} exact path={key} render={(props) => (getComponent(pageInstance, props))} />
                );
            }
        }

        return (
            <LocaleProvider locale={zh_CN}>
                <MemoryRouter>
                    <TabPanelWithRouter wrappedComponentRef={(inst) => this.panelRouter = inst} contentMap={contentMap}>
                        <Switch>
                            {routeList}
                        </Switch>
                        {this.props.children}
                    </TabPanelWithRouter>
                </MemoryRouter>
            </LocaleProvider>
        );
    }
}
